using System;
using UnityEngine;

namespace Voodoo.Meta.RVModules
{
	public class ChestRoomKeysManager : MonoBehaviour
	{
		private const string LasCollectedKeyLevel = "Voodoo_Last_Collected_Key_Level";

		private const string TotalCollectedKey = "Voodoo_Total_Collected_Key";

		[SerializeField]
		private ChestRoomAdapter _chestRoomPanel;

		[SerializeField]
		private KeyCollectable _keyPrefab;

		public int keysNeededToOpen = 3;

		private static ChestRoomKeysManager _instance;

		public int LevelsToWait
		{
			get
			{
				if (KeysCount != 1)
				{
					return 2;
				}
				return 1;
			}
		}

		private int LastCollectedKey
		{
			get
			{
				return NintendoPlayerPrefs.GetInt("Voodoo_Last_Collected_Key_Level", 0);
			}
			set
			{
				NintendoPlayerPrefs.SetInt("Voodoo_Last_Collected_Key_Level", value);
			}
		}

		private int KeysCount
		{
			get
			{
				return NintendoPlayerPrefs.GetInt("Voodoo_Total_Collected_Key", 0);
			}
			set
			{
				NintendoPlayerPrefs.SetInt("Voodoo_Total_Collected_Key", value);
			}
		}

		public int CurrentKeys => KeysCount;

		public static ChestRoomKeysManager Instance
		{
			get
			{
				if (!_instance)
				{
					_instance = UnityEngine.Object.FindObjectOfType<ChestRoomKeysManager>();
				}
				return _instance;
			}
		}

		public event Action onKeyCollected;

		private void Awake()
		{
			if (_instance == null)
			{
				_instance = this;
			}
			else if (_instance != this)
			{
				UnityEngine.Object.Destroy(base.gameObject);
				return;
			}
			UnityEngine.Object.Instantiate(_chestRoomPanel);
		}

		public bool ShouldSpawnKey(int currentLevel)
		{
			if (ChestRoomAdapter.IsInAB() && currentLevel >= 3)
			{
				return currentLevel >= LastCollectedKey + LevelsToWait;
			}
			return false;
		}

		public bool HasEnoughKey()
		{
			return KeysCount >= keysNeededToOpen;
		}

		public void ComputeKeyCollected(int currentLevel)
		{
			LastCollectedKey = currentLevel;
			KeysCount++;
			this.onKeyCollected?.Invoke();
		}

		public void TryOpenChestRoom(Action onClose)
		{
			if (KeysCount >= keysNeededToOpen)
			{
				KeysCount = 0;
				ChestRoomAdapter.Instance.Show(delegate
				{
					onClose?.Invoke();
				});
			}
			else
			{
				onClose?.Invoke();
			}
		}
	}
}
